package com.mdlib.helper.ui.fragments.rush.vicinity;

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.ljlib.core.util.EmptyUtils;
import com.ljlib.core.util.LogUtil;
import com.ljlib.help.R;
import com.mdlib.helper.api.DataManager;
import com.mdlib.helper.api.network.RxHelper;
import com.mdlib.helper.api.network.RxSubscribe;
import com.mdlib.helper.base.BaseTitleFragment;
import com.mdlib.helper.model.AppModel;
import com.mdlib.helper.model.BaseResult;
import com.mdlib.helper.model.entity.StatusEntity;
import com.mdlib.helper.ui.adapter.AddKeywordAdapter;
import com.mdlib.helper.ui.adapter.HeatKeywordAdapter;
import com.mdlib.helper.ui.widget.togglebutton.ToggleButton;
import com.mdlib.helper.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 作者：HQY on 16/11/28 10:07
 * 邮箱：hqy_xz@126.com
 */

public class OrderSetFragment extends BaseTitleFragment {


    @Bind(R.id.tb_order_set_info)
    ToggleButton mTbOrderSetInfo;
    @Bind(R.id.rb_order_set_all)
    RadioButton mRbOrderSetAll;
    @Bind(R.id.rb_order_set_accurate)
    RadioButton mRbOrderSetAccurate;
    @Bind(R.id.et_keyword_content)
    EditText mEtKeywordContent;
    @Bind(R.id.tv_add_keyword)
    TextView mTvAddKeyword;
    @Bind(R.id.rv_keyword_add)
    RecyclerView mRvKeywordAdd;
    @Bind(R.id.rv_heat_keyword)
    RecyclerView mRvHeatKeyword;
    @Bind(R.id.ll_keywrod)
    LinearLayout mLlKeywrod;

    private List<String> addKeywordList = new ArrayList<>();
    private List<String> heatKeywordList = new ArrayList<>();

    private AddKeywordAdapter mAddKeywordAdapter;
    private HeatKeywordAdapter mHeatKeywordAdapter;

    public static OrderSetFragment newInstance() {
        return new OrderSetFragment();
    }


    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_order_set;
    }

    @Override
    protected void initView(View rootView) {
        super.initView(rootView);
        setTitle(R.string.order_set_title, R.color.white)
                .setTitleBgColor(R.color.generic_view_bg)
                .setImgLeftListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        removeFragment();
                    }
                });
        getRunStatus();
        init();

    }

    public void init() {
        heatKeywordList = AppModel.getInstance().getAppFrontInfo().getKeywordList();
        mHeatKeywordAdapter = new HeatKeywordAdapter(heatKeywordList);
        mRvHeatKeyword.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        mRvHeatKeyword.setAdapter(mHeatKeywordAdapter);
        mRvHeatKeyword.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {

            }

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemClick(adapter, view, position);
                setAccurate(setKey(heatKeywordList.get(position)), "add");
            }
        });


        mAddKeywordAdapter = new AddKeywordAdapter(addKeywordList);
//        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
//        layoutManager.setOrientation(new GridLayoutManager(getActivity(), 4));
        mRvKeywordAdd.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
        mRvKeywordAdd.setAdapter(mAddKeywordAdapter);
        mRvKeywordAdd.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {

            }


            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemChildClick(adapter, view, position);
                switch (view.getId()) {
                    case R.id.iv_keyword_close:
                        addKeywordList.remove(position);
                        setAccurate(setKeyTwo(), "del");
                        break;
                    case R.id.tv_keyword_content:
                        break;
                }
            }
        });
        mTbOrderSetInfo.setOnToggleChanged(new ToggleButton.OnToggleChanged() {
            @Override
            public void onToggle(boolean on) {
                if (on) {
                    setSystem("1");
                } else {
                    setSystem("2");
                }
            }
        });


    }


    /**
     * 获取系统信息
     *
     * @param status
     */
    private void setSystem(String status) {
        addSubscribe(DataManager.getInstance().getUserApi()
                .setNotice(status)
                .compose(RxHelper.<BaseResult>rxSchedulerHelper())
                .subscribe(new RxSubscribe<BaseResult>() {
                    @Override
                    protected void onSucc(BaseResult baseResult) {
                        ToastUtil.showToast(baseResult.msg);
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.showToast(msg);
                    }
                }));
    }

    /**
     * 获取接单状态
     */
    private void getRunStatus() {
        startLoadingDialog(true);
        addSubscribe(DataManager.getInstance().getUserApi()
                .getRunStatues()
                .compose(RxHelper.<StatusEntity>defaultHandleResult())
                .subscribe(new RxSubscribe<StatusEntity>() {
                    @Override
                    protected void onSucc(StatusEntity status) {
                        stopLoadingDialog();
                        if (status.getNotice() == 1) {
                            mTbOrderSetInfo.setToggleOn();
                        } else {
                            mTbOrderSetInfo.setToggleOff();
                        }
                        if (status.getAccept_status() == 1) {
                            mLlKeywrod.setVisibility(View.VISIBLE);
                            mRbOrderSetAll.setChecked(false);
                            mRbOrderSetAccurate.setChecked(true);
                            getKeywords();
                        } else {
                            mLlKeywrod.setVisibility(View.GONE);
                            mRbOrderSetAll.setChecked(true);
                            mRbOrderSetAccurate.setChecked(false);
                        }
                    }

                    @Override
                    protected void onFail(String msg) {
                        stopLoadingDialog();
                        ToastUtil.showToast(msg);
                    }
                }));
    }

    @OnClick({R.id.rb_order_set_all, R.id.rb_order_set_accurate, R.id.tv_add_keyword})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rb_order_set_all:
                setOrderRules("2");
                break;
            case R.id.rb_order_set_accurate:
                setOrderRules("1");
                break;
            case R.id.tv_add_keyword:
                String keyword = mEtKeywordContent.getText().toString();
                if (EmptyUtils.isEmpty(keyword)) {
                    ToastUtil.showToast(getActivity().getResources().getString(R.string.generic_et_not_empty));
                    return;
                }
                if (EmptyUtils.isNotEmpty(addKeywordList)) {
                    if (addKeywordList.size() < 30) {
                        setAccurate(setKey(keyword), "add");
                    } else {
                        ToastUtil.showToast(getActivity().getResources().getString(R.string.order_set_keyword_size));
                    }
                }

                break;
        }
    }


    private String setKey(String key) {
        StringBuffer sb = new StringBuffer();
        if (addKeywordList.size() > 1) {
            sb.append(addKeywordList.get(0));
            for (int i = 1; i < addKeywordList.size(); i++) {
                sb.append("|" + addKeywordList.get(i));
            }
            sb.append("|" + key);
        } else {
            sb.append(key);
        }

        return sb.toString();
    }

    private String setKeyTwo() {
        StringBuffer sb = new StringBuffer();
        if (addKeywordList.size() > 1) {
            sb.append(addKeywordList.get(0));
            for (int i = 1; i < addKeywordList.size(); i++) {
                sb.append("|" + addKeywordList.get(i));
            }
        }
        return sb.toString();
    }

    /**
     * 设置接单规则
     *
     * @param status
     */
    private void setOrderRules(final String status) {
        addSubscribe(DataManager.getInstance().getUserApi()
                .setOrderRules(status)
                .compose(RxHelper.<BaseResult>rxSchedulerHelper())
                .subscribe(new RxSubscribe<BaseResult>() {
                    @Override
                    protected void onSucc(BaseResult baseResult) {
                        if (status.equals("2")) {
                            mLlKeywrod.setVisibility(View.GONE);
                            mRbOrderSetAll.setChecked(true);
                            mRbOrderSetAccurate.setChecked(false);
                        } else if (status.equals("1")) {
                            mLlKeywrod.setVisibility(View.VISIBLE);
                            mRbOrderSetAll.setChecked(false);
                            mRbOrderSetAccurate.setChecked(true);
                            getKeywords();
                        }
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.showToast(msg);
                        mLlKeywrod.setVisibility(View.GONE);
                        mRbOrderSetAll.setChecked(true);
                        mRbOrderSetAccurate.setChecked(false);
                    }
                }));
    }

    /**
     * 获取关键字
     */
    private void getKeywords() {
        addSubscribe(DataManager.getInstance().getUserApi()
                .getKeywords()
                .compose(RxHelper.<ArrayList<String>>defaultHandleResult())
                .subscribe(new RxSubscribe<ArrayList<String>>() {
                    @Override
                    protected void onSucc(ArrayList<String> strings) {
                        addKeywordList.clear();
                        addKeywordList = strings;
                        mAddKeywordAdapter.setNewData(addKeywordList);
                        mAddKeywordAdapter.notifyDataSetChanged();

                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.showToast(msg);
                    }
                }));
    }

    private void setAccurate(String key, String type) {
        LogUtil.e("设置关键字:" + key);
        addSubscribe(DataManager.getInstance().getUserApi()
                .setAccurate(key, type)
                .compose(RxHelper.<BaseResult>rxSchedulerHelper())
                .subscribe(new RxSubscribe<BaseResult>() {
                    @Override
                    protected void onSucc(BaseResult baseResult) {
                        ToastUtil.showToast(baseResult.msg);
                        getKeywords();
                        mAddKeywordAdapter.notifyDataSetChanged();
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.showToast(msg);

                    }
                }));
    }


}
